#!/usr/bin/perl
#
# db_send.pl - sends flags and stores it into database
#

use strict;
use mod_db;
use constant 
{
	DEBUG		=> 1,
	TEAM_ID 	=> 19,			# !!! Don't forget to change
	FILE_LOG	=> 'db_send.log',
	FILE_DB		=> 'db_send.db',
};

my %ret_msg =
(
        0       => 'INT ERR         ',
        1       => 'NOT ACC, TRY    ',
        2       => 'NOT ACC, NOT TRY',
        3       => 'ACCEPTED        ',
);

my $LOG;

sub write_log
{
	my ( $time, $msg ) = ( ''.gmtime, shift );
	return unless defined $msg;
	print ( $LOG  "[ $time ] $msg\n" ) or die "db_send: syswrite failed: $!\n";
}

db_init( FILE_DB );
open $LOG, ">> " . FILE_LOG		or die "db_send.pl: error: can't open '" . FILE_LOG ."'\n";

my $tid = TEAM_ID;
print "db_send.pl: team_id is $tid\n"			if DEBUG;
write_log "db_send started, team_id: $tid";

my $cmd = 'wc -lc ' . FILE_DB;
chomp( my $size = `$cmd` );
write_log( "database: " . $size );

############ Reading flags

my @flags = <STDIN>;
chomp for @flags;
my $flags_total = @flags;

########### Removing existing flags

@flags = grep { !db_exists( $_ ) } @flags;
my $flags_new = @flags;

########### Sending

my $flags_accepted = 0;

for ( @flags )
{
	( my $out = `./send_one.pl $tid $_` ) =~ s/[\r\n]//g;
	my $ret_val = $? >> 8;

	write_log "$_: $ret_val: $ret_msg{$ret_val}: $out";

	print "db_send.pl: $_ :$ret_val :$ret_msg{$ret_val}:  $out\n"	if DEBUG;

	++$flags_accepted 	if $ret_val == 3;
	if ( $ret_val == 2 || $ret_val == 3 )
	{
		db_store( $_ );
		write_log "added to database";
	}
}

print "db_send.pl: flags: [tot: $flags_total, new: $flags_new, acc: $flags_accepted]\n";
write_log "db_send.pl: flags: [tot: $flags_total, new: $flags_new, acc: $flags_accepted]";

# Closing files

close $LOG;
